import axios, {
  AxiosHeaders,
  AxiosInstance,
  AxiosRequestConfig,
  AxiosResponse,
  AxiosError,
  InternalAxiosRequestConfig 
} from 'axios';

// 定义基础响应结构
export interface ApiResponse<T = any> {
  code: number;
  data: T;
  message?: string;
  [key: string]: any; // 允许扩展字段
}

// 创建带类型的 Axios 实例
const createApiClient = (config?: AxiosRequestConfig): AxiosInstance => {
  const apiClient = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_URL,
    timeout: 10000,
    headers: {
      'Content-Type': 'application/json',
      'clientid': 'e5cd7e4891bf95d1d19206ce24a7b32e'
    },
    ...config,
  });

  // 请求拦截器
  apiClient.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
      const token = localStorage.getItem('authToken');
      if (token) {
        if (config.headers instanceof AxiosHeaders) {
          config.headers.set('Authorization', `Bearer ${token}`);
        } else {
          config.headers = {
            ...config.headers,
            Authorization: `Bearer ${token}`,
          };
        }
      }
      return config;
    },
    (error: AxiosError) => Promise.reject(error)
  );

  // 响应拦截器
  apiClient.interceptors.response.use(
    (response: AxiosResponse<ApiResponse>) => {
      // 如果后端使用统一响应结构，直接返回 data 部分
      const errorMessage = response.data?.msg || '请求错误';
      switch (response.data?.code) {
        case 200:
          return response.data;
          break;
        case 401:
          console.log(window.location.pathname)
          window.location.href = '/login?redirectPath=' + encodeURIComponent(window.location.pathname);
          break;
        case 403:
          console.error('权限不足:', errorMessage);
          break;
        default:
          console.error(`HTTP 错误 ${status}:`, errorMessage);
      }
    },
    (error: AxiosError<ApiResponse>) => {
      console.log(error)
      // 统一错误处理
      if (error.response) {
        const { status, data } = error.response;
        const errorMessage = data?.message || '请求错误';
        
        switch (status) {
          case 401:
            window.location.href = '/login';
            break;
          case 403:
            console.error('权限不足:', errorMessage);
            break;
          default:
            console.error(`HTTP 错误 ${status}:`, errorMessage);
        }
      } else {
        console.error('网络错误:', error.message);
      }
      return Promise.reject(error);
    }
  );

  return apiClient;
};

export const apiClient = createApiClient();

export const get = <T = any>(
  url: string,
  params?: object,
  config?: AxiosRequestConfig
): Promise<T> => {
  return apiClient.get<T>(url, { ...config, params }).then((response) => response.data);
};

export const post = <T = any>(
  url: string,
  data?: object,
  config?: AxiosRequestConfig
): Promise<T> => {
  return apiClient.post<T>(url, data, config).then((response) => response.data);
};

export const put = <T = any>(
  url: string,
  data?: object,
  config?: AxiosRequestConfig
): Promise<T> => {
  return apiClient.put<T>(url, data, config).then((response) => response.data);
};

export const del = <T = any>(
  url: string,
  config?: AxiosRequestConfig
): Promise<T> => {
  return apiClient.delete<T>(url, config).then((response) => response.data);
};